package com.example.warehousems.controller;

import com.example.warehousems.component.BaseResponse;
import com.example.warehousems.component.UserInfo;
import com.example.warehousems.dao.UserRepository;
import com.example.warehousems.dao.model.User;
import com.example.warehousems.service.UserService;
import com.example.warehousems.vo.PartialUpdateUserVO;
import com.example.warehousems.vo.UserBaseVO;
import com.example.warehousems.vo.UserRegisterVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("login")
    public BaseResponse login(@RequestBody @Validated UserBaseVO userBaseVO) {
        System.out.println(userBaseVO);
        return userService.login(userBaseVO.getUsername(), userBaseVO.getPassword());
    }

    @GetMapping("/token")
    public BaseResponse getNewToken(@RequestBody String refreshToken) {
        return BaseResponse.success(userService.getNewToken(refreshToken));
    }

    @PostMapping("/")
    BaseResponse register(@RequestBody UserRegisterVO userRegisterVO) {
        System.out.println(userRegisterVO);
        String username = userRegisterVO.getUsername();
        String password = userRegisterVO.getPassword();
        String checkPassword = userRegisterVO.getCheckPassword();
        String email = userRegisterVO.getEmail();

        if (!password.equals(checkPassword))
            return BaseResponse.error("两次密码不一致");

        return userService.register(username, password, email);
    }

    @PatchMapping("/password")
    BaseResponse changePassword(@RequestBody @Validated UserBaseVO userBaseVO) {
        return userService.changePassword(userBaseVO.getUsername(), userBaseVO.getPassword());
    }

    @PostMapping("/info")
    BaseResponse info(@RequestHeader("Authorization") String token) {
        return userService.info(token);
    }

    @PostMapping("/logout")
    BaseResponse logout() {
        return userService.logout();
    }

    @GetMapping("")
    BaseResponse getAllUsers() {
        return userService.getAllUsers();
    }

    @PutMapping("/{id}")
    BaseResponse updateUser(@PathVariable("id") Integer id, @RequestBody User user) {
        return userService.updateUser(id, user);
    }

    @PatchMapping("/{id}")
    BaseResponse updateUserRole(@PathVariable("id") Integer id, @RequestBody PartialUpdateUserVO user) {
        return userService.updateUserInfo(id, user);
    }

    @DeleteMapping("/{id}")
    BaseResponse deleteUser(@PathVariable("id") Integer id) {
        return userService.deleteUser(id);
    }
}
